﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text.RegularExpressions;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Net;
using OA.Log;

/// <summary>
///Zolf 的摘要说明
/// </summary>
public class Zolf
{
    public Zolf()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }


    #region 字符串处理
    /// <summary>
    /// 分解url取得参数值
    /// </summary>
    /// <param name="urlstr">Url地址</param>
    /// <param name="ParamaterName">参数名</param>
    /// <returns>参数值</returns>
    public static string UrlRequest(string urlstr, string ParamaterName)
    {
        int intpots = urlstr.IndexOf("?");
        string strRight = urlstr.Substring(intpots + 1);
        string[] arrTmp = strRight.Split('&');
        for (int i = 0; i < arrTmp.Length; i++)
        {
            string[] arrTemp = arrTmp[i].Split('=');
            if (arrTemp[0].ToString().ToLower() == ParamaterName.ToLower())
                return arrTemp[1].ToString();
        }
        return "";
    }

 
    /// <summary>
    /// 弹出消息提示对话框，并进行页面跳转。当URL为BACK时，页面将退到上一页，当URL为CLOSE时，则关闭窗口。
    /// </summary>
    /// <param name="page">当前页面指针，一般为this</param>
    /// <param name="msg">提示信息</param>
    /// <param name="url">跳转的目标URL。当URL为BACK时，页面将退到上一页，当URL为CLOSE时，则关闭窗口。</param>
    public static void ShowAlertAndRedirectScript(Page page, string msg, string url)
    {
        StringBuilder Builder = new StringBuilder();
        Builder.Append("<script language='javascript' defer>");
        Builder.AppendFormat("alert('{0}');", msg);

        switch (url.ToUpper())
        {
            case "BACK":
                Builder.Append("history.go(-1);");
                break;

            case "CLOSE":
                Builder.Append("window.close();");
                break;

            default:
                Builder.AppendFormat("top.location.href='{0}'", url);
                break;
        }
        Builder.Append("</script>");
        page.ClientScript.RegisterStartupScript(page.GetType(), "message", Builder.ToString());

    }

    /// <summary>
    /// 取前count个字符,后面+str2
    /// </summary>
    /// <param name="str">源字符串</param>
    /// <param name="count">截取长度</param>
    /// <param name="str2">后加标记eg：..</param>
    /// <returns>返回截取后的串</returns>
    public static string GetCountStr(string str, int count, string str2)
    {
        if (str.Length <= count)
        {
            return str;
        }
        else
        {
            return str.Substring(0, count) + str2;
        }
    }



    //截取指定长度字符 
    public static string Cut_str(string str, int len)
    {
        try
        {
            int _a = 0;
            int _b = 0;
            string _s = "";
            for (int _i = 0; _i < str.Length; _i++)
            {
                _b += 1;
                if (new Regex("^[ \\u4E00-\\u9FAF]+$").IsMatch(str.Substring(_i, 1)))
                {
                    _a += 2;
                }
                else
                {
                    _a++;
                }
                if (_a == len)
                {
                    _s = str.Substring(0, _b);
                    break;
                }
                else if (_a > len)
                {
                    _s = str.Substring(0, (_b - 1)) + ".";
                    break;
                }
            }
            return _s;
        }
        catch (Exception e)
        {

            Logger.LogError(e.Message);
        }
        return null;
    }


    /// <summary>
    /// MD5加密
    /// </summary>
    /// <param name="str">源串</param>
    /// <returns>加密后的串</returns>
    public static string GetMD5Password(string str)
    {
        try
        {
            byte[] hashvalue = (new MD5CryptoServiceProvider()).ComputeHash(Encoding.UTF8.GetBytes(str));
            return BitConverter.ToString(hashvalue);
        }
        catch
        {
            return String.Empty;
        }

    }

    #endregion 字符串处理

    #region 时间串处理
    /// <summary>
    /// 修改时间格式
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string GetShortDateTime(string str)
    {
        try
        {
            return Convert.ToDateTime(str).ToString("yyyy-MM-dd");
        }
        catch
        {
            return "";
        }
    }

    /// <summary>
    /// 按格式返回时间串
    /// </summary>
    /// <param name="str"></param>
    /// <param name="TypeStr"></param>
    /// <returns></returns>
    public static string GetDateTimeType(string str, string TypeStr)
    {
        try
        {
            return Convert.ToDateTime(str).ToString(TypeStr);
        }
        catch
        {
            return "";
        }
    }

    #endregion 时间串处理

    #region cookies session处理

    /// <summary>
    /// 写cookie值
    /// </summary>
    /// <param name="strName">名称</param>
    /// <param name="strValue">值</param>
    /// <param name="expires">cookies过期时间（小时数）</param>
    public static void WriteCookie(string strName, string strValue, string expires)
    {
        HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
        if (cookie == null)
        {
            cookie = new HttpCookie(strName);
        }
        cookie.Value = HttpUtility.UrlEncode(strValue);
        if (expires != "")
        {
            cookie.Expires = DateTime.Now.AddDays(Convert.ToDouble(expires));
        }
        HttpContext.Current.Response.AppendCookie(cookie);
    }

    /// <summary>
    /// 读cookie值
    /// </summary>
    /// <param name="strName">名称</param>
    /// <returns>cookie值</returns>
    public static string GetCookie(string strName)
    {
        if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
        {
            return HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies[strName].Value.ToString());
        }
        return "";
    }









    /// <summary>
    /// 往cookies中追加最新历史记录
    /// </summary>
    /// <param name="cookiesName">cookie名称</param>
    /// <param name="cookiesValue">追加的值</param>
    /// <param name="ExpiresDays">过期时间（天数）</param>
    public static void AddToCookies(string cookiesName, string cookiesValue, int ExpiresDays)
    {
        HttpCookie cookie = HttpContext.Current.Request.Cookies[cookiesName];
        if (cookie == null)
        {
            cookie = new HttpCookie(cookiesName);
            cookie.Value = cookiesValue;
            cookie.Expires = DateTime.Now.AddDays(ExpiresDays);
        }
        else
        {
            string[] strs = System.Web.HttpContext.Current.Server.UrlDecode(GetCookie(cookiesName)).Split(',');
            string tmpstr = cookiesValue;
            int length = 3;//最多存3条记录
            if (strs.Length < length)
            {
                length = strs.Length;
            }
            for (int i = 0; i < length; i++)
            {
                if (strs[i] != cookiesValue)
                {
                    tmpstr = tmpstr + "," + strs[i];
                }
            }
            cookie.Value = tmpstr;
            cookie.Expires = DateTime.Now.AddDays(ExpiresDays);
        }
        HttpContext.Current.Response.AppendCookie(cookie);
    }

    #endregion cookies session处理

    #region 字符串HTML处理

    /// <summary>
    /// 移除Html标记
    /// </summary>
    /// <param name="content"></param>
    /// <returns></returns>
    public static string RemoveHtml(string content)
    {
        content = content.Replace("\n", "");
        content = content.Replace("\r", "");
        string regexstr = @"<[^>]*>";
        return Regex.Replace(content, regexstr, string.Empty, RegexOptions.IgnoreCase);
    }

    /// <summary>
    /// 屏蔽A标签
    /// </summary>
    /// <returns></returns>
    public static string RemoveHtmlA(string str)
    {
        string regexstr = @"<a[^>]*>";
        str = Regex.Replace(str.ToLower(), regexstr, string.Empty, RegexOptions.IgnoreCase);
        return str.Replace("</a>", "");
    }


    /// <summary>
    /// 突出显示关键字
    /// </summary>
    /// <param name="contentstr"></param>
    /// <param name="Key"></param>
    /// <returns></returns>
    public static string GetAddHtml(string contentstr, string Key)
    {
        if (contentstr != "" && Key != null && Key != "")
        {
            contentstr = contentstr.Replace(Key, "<font color=\"#ffb72c\" style=\"font-weight:bold;\">" + Key + "</font>");
            return contentstr;
        }
        return contentstr;
    }

    #endregion 字符串HTML处理

    #region 图片或文件处理
    /// <summary>
    /// 如何文件存在则返回，不存在则替换
    /// </summary>
    /// <param name="getURL">取得的图片地址</param>
    /// <param name="defaultURL">默认图片地址</param>
    /// <returns>图片地址</returns>
    public static string GetDefualtPic(string getURL, string defaultURL)
    {
        if (File.Exists(getURL) || GetFileIsExist(getURL))
        {
            return getURL;
        }
        else
        {
            return defaultURL;
        }
    }

    /// <summary>
    /// 如何文件存在则返回，不存在则替换
    /// </summary>
    /// <param name="getURL">取得的图片地址</param>
    /// <param name="defaultURL">默认图片地址</param>
    /// <returns>图片地址</returns>
    public static string GetDefualtPic(string getURL, string defaultURL, string ismen)
    {
        if (File.Exists(getURL) || GetFileIsExist(getURL))
        {
            return getURL;
        }
        else
        {
            if (ismen == "True")
            {
                return "Images/manHeadx.jpg";
            }
            else if (ismen == "False")
            {
                return "Images/womanHeadx.jpg";
            }
            else
            {
                return "Images/logo3.gif";
            }

        }
    }


    /// <summary>
    /// 取得远程的文件是否存在
    /// </summary>
    /// <param name="uri">文件远程地址</param>
    /// <returns>存在返回true 不存在返回false</returns>
    public static bool GetFileIsExist(string uri)
    {
        HttpWebRequest req = null;
        HttpWebResponse res = null;
        try
        {
            req = (HttpWebRequest)WebRequest.Create(uri);
            req.Method = "HEAD";
            req.Timeout = 100;
            res = (HttpWebResponse)req.GetResponse();
            return (res.StatusCode == HttpStatusCode.OK);
        }
        catch
        {
            return false;
        }
        finally
        {
            if (res != null)
            {
                res.Close();
                res = null;
            }
            if (req != null)
            {
                req.Abort();
                req = null;
            }
        }
    }

    #endregion 其他

    #region 对话框
    /// <summary>
    ///弹出对话框并跳转；
    /// </summary>
    /// <param name="str_Message"></param>
    /// <param name="redirect"></param>
    public static void Alert_url(string str_Message, string redirect)
    {
        ClientScriptManager scriptManager = ((Page)System.Web.HttpContext.Current.Handler).ClientScript;
        scriptManager.RegisterStartupScript(typeof(string), "", "alert('" + str_Message + "');self.location='" + redirect + "'", true);
    }


    /// <summary>
    /// 弹出对话框
    /// </summary>
    /// <param name="str_Message"></param>
    public static void Alert(string str_Message)
    {
        ClientScriptManager scriptManager = ((Page)System.Web.HttpContext.Current.Handler).ClientScript;
        scriptManager.RegisterStartupScript(typeof(string), "", "alert('" + str_Message + "');", true);
    }
    #endregion 对话框


}
